package com.pengcheng.taskapplication.net;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;

import com.pengcheng.taskapplication.mvp.view.widget.LoadingDialog;
import com.pengcheng.taskapplication.mvp.view.widget.ProgressDialog;

public class ProgressDialogHandler extends Handler {
    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;
    private ProgressDialog pd;

    private Context context;
    private boolean cancelable;
    ProgressCancelListener mProgressCancelListener;

    private boolean isNoDialog;

    public boolean isNoDialog() {
        return isNoDialog;
    }

    public void setNoDialog(boolean noDialog) {
        isNoDialog = noDialog;
    }

    public ProgressDialogHandler(Context context, ProgressCancelListener mProgressCancelListener, boolean cancelable) {
        super();
        this.context = context;
        this.mProgressCancelListener = mProgressCancelListener;
        this.cancelable = cancelable;
    }


    private void initProgressDialog() {
        if (pd == null) {
            pd = ProgressDialog.createDialog((Activity) context); /**/
            pd.setCancelable(cancelable);
            if (cancelable) pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    mProgressCancelListener.onCancelProgress();
                }
            });
            if (!pd.isShowing()) {
                if(!((Activity)context).isFinishing())
                pd.show();
            }
        }
    }

    private void dismissProgressDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SHOW_PROGRESS_DIALOG:
                initProgressDialog();
                break;
            case DISMISS_PROGRESS_DIALOG:
                dismissProgressDialog();
                break;
        }
    }
}